import {defineComponent, ref, onMounted} from 'vue'
import ace from "ace-builds";
import 'ace-builds/src-min-noconflict/theme-sqlserver' // 新设主题
import 'ace-builds/src-min-noconflict/mode-javascript' // 默认设置的语言模式
import 'ace-builds/src-min-noconflict/mode-json' //
import 'ace-builds/src-min-noconflict/mode-css' //
import 'ace-builds/src-min-noconflict/ext-language_tools'
import 'ace-builds/src-min-noconflict/ext-beautify'
import aceEditorClasses from './aceEditor.module.scss'

export default defineComponent({
    setup() {
        const aceEditor = ref<Element | string>('')
        let editor: any = null
        onMounted(() => {
            console.log(aceEditor.value instanceof Element)
            editor = ace.edit(aceEditor.value);
            editor.setTheme("ace/theme/sqlserver");
            editor.getSession().setMode("ace/mode/javascript");
            editor.getSession().setUseWrapMode(true);// 设置是否启用换行
            editor.getSession().setTabSize(2);
            editor.getSession().setUseSoftTabs(true); //
            editor.getSession().setUseWorker(false); // 启用辅助程序

            // 复制，复制到剪贴板
            editor.commands.addCommand({
                name: 'copy',
                bindKey: {win: 'Ctrl-C', mac: 'Command-C'},
                exec: async function (editor) {
                    const selectedText = editor.getSelectedText();
                    try {
                        await navigator.clipboard.writeText(selectedText);
                        console.log('文本已复制到剪贴板');
                    } catch (err) {
                        console.error('复制失败:', err);
                    }
                }
            });
            // 粘贴，粘贴到编辑器
            editor.commands.addCommand({
                name: 'paste',
                bindKey: {win: 'Ctrl-V', mac: 'Command-V'},
                exec: function (editor) {
                    // 从剪贴板中获取文本
                    navigator.clipboard.readText().then(text => {
                        // 将文本插入到编辑器中
                        editor.insert(text);
                    });
                }
            });
            
        });


        const copy = function () {
            editor.execCommand('copy')
        }
        const paste = function () {
            editor.execCommand('paste')
        }
        const selectall = function () {
            // 获取编辑器的选区对象
            let selection = editor.getSelection();
            // 选择文本
            selection.selectAll(); // 选择全部文本
        }
        return () => (
            <div class="flex">
                <div ref={aceEditor} class={aceEditorClasses.aceEditor}></div>
                <div class="flex">
                    <el-button onClick={copy}>复制</el-button>
                    <el-button onClick={paste}>粘贴</el-button>
                    <el-button onClick={selectall}>全选</el-button>
                </div>
            </div>
        );
    },
})
